import base64
import json


def decode_base64(encoded_string):
    """
    解密Base64编码的字符串

    Args:
        encoded_string (str): Base64编码的字符串

    Returns:
        dict/list: 解码后的数据（如果是JSON格式）
        str: 解码后的原始字符串（如果不是JSON格式）
    """
    try:
        # 添加缺失的填充字符（=）
        padding = 4 - len(encoded_string) % 4
        if padding != 4:
            encoded_string += '=' * padding

        # Base64解码
        decoded_bytes = base64.b64decode(encoded_string)
        decoded_string = decoded_bytes.decode('utf-8')

        # 尝试解析为JSON
        try:
            return json.loads(decoded_string)
        except json.JSONDecodeError:
            return decoded_string

    except Exception as e:
        print(f"解码失败: {e}")
        return None


def encode_base64(data):
    """
    将数据编码为Base64字符串

    Args:
        data (dict/list/str): 要编码的数据

    Returns:
        str: Base64编码的字符串
    """
    try:
        # 如果是字典或列表，先转换为JSON字符串
        if isinstance(data, (dict, list)):
            data = json.dumps(data, ensure_ascii=False)

        # 编码为bytes
        data_bytes = data.encode('utf-8')

        # Base64编码
        encoded_bytes = base64.b64encode(data_bytes)
        return encoded_bytes.decode('utf-8')

    except Exception as e:
        print(f"编码失败: {e}")
        return None


# 使用示例
if __name__ == "__main__":
    # 你的加密字符串
    encoded_str = "W3sibmFtZSI6InByb2dyYW1pbmcucmVnaW9uIiwiaXNFbmFibGVkIjp0cnVlLCJmb2xkU3RhdGUiOiJVbkZvbGQiLCJpbnB1dHMiOnsiY29udGVudCI6eyJ2YWx1ZSI6IjEwOuWIneWni+WMliJ9fSwib3V0cHV0cyI6e30sIl9fa2luZF9fIjowfSx7Im5hbWUiOiJkaWFsb2cuc2hvd19jdXN0b21fZGlhbG9nIiwiaXNFbmFibGVkIjp0cnVlLCJpbnB1dHMiOnsic2V0dGluZ3MiOnsidmFsdWUiOiIxMDp7XCJkaWFsb2dUaXRsZVwiOm51bGwsXCJoZWlnaHRcIjowLFwid2lkdGhcIjowLFwidGltZW91dFwiOjAsXCJhdXRvQ2xvc2VCdXR0b25cIjpudWxsLFwidXNlX3dhaXRfdGltZW91dFwiOmZhb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SJ9LCJ3YWl0X3NlY29uZHMiOnsidmFsdWUiOm51bGx9fSwib3V0cHV0cyI6eyJidXR0b25fcmVzdWx0Ijp7Im5hbWUiOiJwcmVzc2VkX2J1dHRvbiIsImlzRW5hYmxlIjp0cnVlfX0sIl9fa2luZF9fIjowfSx7Im5hbWUiOiJwcm9jZXNzLmV4aXQiLCJpc0VuYWJsZWQiOnRydWUsImlucHV0cyI6e30sIm91dHB1dHMiOnt9LCJfX2tpbmRfXyI6MH0seyJuYW1lIjoid29ya2Zsb3cuZW5kaWYiLCJpc0VuYWJsZWQiOnRydWUsImlucHV0cyI6e30sIm91dHB1dHMiOnt9LCJfX2tpbmRfXyI6MH0seyJuYW1lIjoicHJvZ3JhbWluZy5lbmRyZWdpb24iLCJpc0VuYWJsZWQiOnRydWUsImlucHV0cyI6e30sIm91dHB1dHMiOnt9LCJfX2tpbmRfXyI6MH1d"

    # 解密
    decoded_data = decode_base64(encoded_str)

    if decoded_data:
        print("解密成功！")
        print("=" * 50)

        # 格式化输出JSON
        print(json.dumps(decoded_data, ensure_ascii=False, indent=2))

        # 测试编码功能
        print("\n" + "=" * 50)
        print("编码测试:")
        re_encoded = encode_base64(decoded_data)
        print(f"重新编码后的字符串长度: {len(re_encoded)}")
        print(f"与原字符串相同: {re_encoded == encoded_str}")